<?php 
namespace Home\Controller;
use Think\Controller;

/**
* 发送手机短信验证码静态类，参考短信平台DEMO
* 生成随机6位数字,作为验证码存入SESSION
* 转化短信接口返回的xml为array
*/

class SmsController extends Controller {

//发送短信验证码
    public function sendmassage(){
            $mobile  = $_POST['mobile'];
            $code    = $this->code();
            $target  = "http://106.ihuyi.cn/webservice/sms.php?method=Submit";
            $post_data = "account=cf_dldh&password=JXHC_2014dahua&mobile=".$mobile."&content=".rawurlencode("您的验证码是：".$code."。请不要把验证码泄露给其他人。如非本人操作，可不用理会！大连大华祝您幸福快乐，吉祥如意！");
            $gets    =  $this->xml_to_array($this->Post($post_data, $target));
			
			/*测试用代码
			//$gets  = array();
			//$gets['SubmitResult']['code'] = 404;
			//print_r($gets);
			*/
			
			//$gets['code']短信接口返回值为2时，发送成功,返回值为4085时，次数超限
            if($gets['code']==2){
                $_SESSION['mobile'] = $mobile;
                $_SESSION['code']   = $code;
				$this->ajaxReturn($gets['code']);
            }elseif($gets['code']==4085){
				$this->ajaxReturn($gets['code']);
			}
		
        
    }
	
//生成短信验证码
	function code($length = 6 , $numeric = 0) {
        PHP_VERSION < '4.2.0' && mt_srand((double)microtime() * 1000000);
        if($numeric) {
            $hash = sprintf('%0'.$length.'d', mt_rand(0, pow(10, $length) - 1));
        } else {
            $hash  = '';
            $chars = '01234567899876543210';
            $max   = strlen($chars) - 1;
            for($i = 0; $i < $length; $i++) {
                $hash .= $chars[mt_rand(0, $max)];
            }
        }
        return $hash;
    }
	

//请求短信验证码发送网址
	function Post($curlPost,$url){
            $curl = curl_init();
            curl_setopt($curl, CURLOPT_URL, $url);
            curl_setopt($curl, CURLOPT_HEADER, false);
            curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($curl, CURLOPT_NOBODY, true);
            curl_setopt($curl, CURLOPT_POST, true);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $curlPost);
            $return_str = curl_exec($curl);
            curl_close($curl);
            return $return_str;
    }

//将 xml数据转换为数组格式。
    function xml_to_array($xml){
        libxml_disable_entity_loader(true);
        $arr = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true); 
        return $arr;
    }

}

?>